<template>
  <div>
    <el-dialog :title="title" :visible="visible" @close="handleClose" width="800px">
      <el-form :model="form" label-position="right" :rules="rules" ref="formRef">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="仓库编码" :label-width="formLabelWidth" prop="stoCode">
              <el-input v-model="form.stoCode"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库名称" :label-width="formLabelWidth" prop="stoName">
              <el-input v-model="form.stoName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库类型" :label-width="formLabelWidth" prop="stoTypeName">
              <el-select clearable v-model="form.stoTypeName" style="width: 100%;" @change="handleTypeChange">
                <el-option v-for="(item, index) in warehouseTypeList" :key="index" :value="item.typeName"
                           :label="item.typeName">
                  <span style="float: left">{{ item.typeName }}</span>
                  <img v-if="item.iconPath" :src="item.iconPath" style="float: right; width: 20px; height: 20px; margin-top: 2px;" />
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态" :label-width="formLabelWidth" prop="enableState">
              <el-switch v-model="form.enableState" active-text="启用" inactive-text="停用" :active-value="'1'"
                         :inactive-value="'0'">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  wareAdd, //仓库新增
  update, //仓库修改
} from '@/api/index/yxl.js'
import { getAllWarehouseTypes } from '@/api/index/warehouseType.js'

export default {
  data() {
    return {
      form: {
        stoCode: '',
        stoName: '',
        enableState: '0',
        stoTypeName: '',
        picPath: ''
      },
      warehouseTypeList: [],//仓库类型列表
      title: '',
      formLabelWidth: '80px',
      rules: {
        stoCode: [{
          required: true,
          message: '请输入仓库编码',
          trigger: 'blur'
        }],
        stoName: [{
          required: true,
          message: '请输入仓库名称',
          trigger: 'blur'
        }],
        enableState: [{
          required: true,
          message: '请选择启用状态',
          trigger: 'blur'
        }],
        stoTypeName: [{
          required: true,
          message: '请选择仓库类型',
          trigger: 'change'
        }],
      }
    }
  },
  props: ['visible'],
  created() {
    this.getWarehouseTypeList();
  },
  methods: {
    //获取仓库类型列表
    getWarehouseTypeList() {
      getAllWarehouseTypes().then(res => {
        this.warehouseTypeList = res.data || [];
      })
    },
    //仓库类型改变时，自动更新图标
    handleTypeChange(typeName) {
      const selectedType = this.warehouseTypeList.find(t => t.typeName === typeName);
      this.form.picPath = selectedType && selectedType.iconPath ? selectedType.iconPath : '';
    },
    openDialog(type, val) {
      this.title = type === 'edit' ? '编辑仓库' : '新增仓库';
      // 根据类型区分新增和编辑逻辑
      if (type === 'edit' && val) {
        this.form = {
          stoId: val.stoId,
          stoCode: val.stoCode,
          stoName: val.stoName,
          enableState: val.enableState,
          stoTypeName: val.stoTypeName || val.sto_type_name || '',
          picPath: val.picPath || val.pic_path || ''
        };
      } else {
        this.form = {
          stoCode: '',
          stoName: '',
          enableState: '0',
        };
      }
    },
    // 提取重置表单的逻辑
    handleClose() {
      this.$nextTick(() => {
        this.$refs.formRef.resetFields();
      })
      // 通过事件通知父组件更新visible值，触发update:visible事件
      this.$emit('update:visible', false);
    },
    //提交表单
    submit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const apiMethod = this.title === '新增仓库' ? wareAdd : update;
          // 调用相应的 API 方法
          this.form.picClassId = String(this.form.picClassId);
          apiMethod(this.form).then(res => {
            this.$emit('addSuccess'); // 通知父组件添加成功
            this.$message({
              message: res.msg, // 显示成功消息
              type: 'success',
            });
            // 提交成功后可以选择清空表单
            this.handleClose();
          }).catch(err => {
            this.$message({
              message: err?.msg || '操作失败', // 捕获错误信息
              type: 'error',
            });
          });
        } else {
          // 校验失败
          return false;
        }
      });
    }
  }
}
</script>

<style></style>
